document.addEventListener('DOMContentLoaded', function() {
    const BASE_URL = window.BASE_URL || '/AVR';
    const addServiceBtn = document.getElementById('add-service-btn');
    const addServiceModal = document.getElementById('add-service-modal');
    const closeAddModal = document.getElementById('close-add-modal');
    const cancelAddBtn = document.getElementById('cancel-add');
    const addServiceForm = document.getElementById('add-service-form');
    const imagePreview = document.getElementById('image-preview');
    const audioPreview = document.getElementById('audio-preview');

    // 打开添加服务模态框
    if (addServiceBtn) {
        addServiceBtn.addEventListener('click', () => {
            addServiceModal.style.display = 'flex';
        });
    }

    // 关闭添加服务模态框
    if (closeAddModal) {
        closeAddModal.addEventListener('click', () => {
            addServiceModal.style.display = 'none';
            resetAddForm();
        });
    }

    if (cancelAddBtn) {
        cancelAddBtn.addEventListener('click', () => {
            addServiceModal.style.display = 'none';
            resetAddForm();
        });
    }

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === addServiceModal) {
            addServiceModal.style.display = 'none';
            resetAddForm();
        }
    });

    // 图片上传预览
    const imageInput = document.getElementById('add-images');
    if (imageInput) {
        imageInput.addEventListener('change', function(e) {
            imagePreview.innerHTML = '';
            const files = e.target.files;

            for (let i = 0; i < Math.min(files.length, 3); i++) {
                const file = files[i];
                const reader = new FileReader();

                reader.onload = function(e) {
                    const previewItem = document.createElement('div');
                    previewItem.className = 'image-preview-item';
                    previewItem.innerHTML = `
                        <img src="${e.target.result}" alt="预览图片">
                        <div class="remove-file" data-index="${i}">&times;</div>
                    `;
                    imagePreview.appendChild(previewItem);

                    // 添加删除图片事件
                    previewItem.querySelector('.remove-file').addEventListener('click', function() {
                        previewItem.remove();
                        // 从文件列表中移除
                        const dataTransfer = new DataTransfer();
                        const inputFiles = document.getElementById('add-images').files;

                        for (let j = 0; j < inputFiles.length; j++) {
                            if (j !== parseInt(this.getAttribute('data-index'))) {
                                dataTransfer.items.add(inputFiles[j]);
                            }
                        }

                        document.getElementById('add-images').files = dataTransfer.files;
                    });
                };

                reader.readAsDataURL(file);
            }
        });
    }

    // 音频上传预览
    const audioInput = document.getElementById('add-audio');
    if (audioInput) {
        audioInput.addEventListener('change', function(e) {
            audioPreview.innerHTML = '';
            const file = e.target.files[0];

            if (file) {
                const previewItem = document.createElement('div');
                previewItem.className = 'audio-preview-item';
                previewItem.innerHTML = `
                    <i class="fas fa-volume-up"></i>
                    <div>${file.name}</div>
                    <div class="remove-file">&times;</div>
                `;
                audioPreview.appendChild(previewItem);

                // 添加删除音频事件
                previewItem.querySelector('.remove-file').addEventListener('click', function() {
                    previewItem.remove();
                    document.getElementById('add-audio').value = '';
                });
            }
        });
    }

    // 上传文件到OSS (修复版)
    async function uploadFileToOss(file, policy, dir) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();

            // 确保目录格式正确
            const normalizedDir = dir.endsWith('/') ? dir : dir + '/';
            const key = normalizedDir + file.name;

            formData.append('key', key);
            formData.append('policy', policy.policy);
            formData.append('OSSAccessKeyId', policy.accessid);
            formData.append('signature', policy.signature);
            formData.append('success_action_status', '200'); // 成功返回200
            formData.append('file', file);

            // 添加安全头
            formData.append('x-oss-security-token', '');
            formData.append('x-oss-object-acl', 'public-read');

            // 调试信息
            console.log('Uploading to OSS:', {
                host: policy.host,
                key: key,
                file: file.name,
                size: file.size
            });

            fetch(policy.host, {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (response.status === 200) {
                        // 构建文件URL - 使用policy.host确保格式正确
                        const fileUrl = `${policy.host}/${key}`;
                        console.log('Upload success:', fileUrl);
                        resolve(fileUrl);
                    } else {
                        response.text().then(text => {
                            console.error('OSS Upload Error:', text);
                            reject(`上传失败: ${response.status} - ${text}`);
                        });
                    }
                })
                .catch(error => {
                    console.error('Upload Error:', error);
                    reject(`上传错误: ${error.message}`);
                });
        });
    }

    // 表单提交处理 (增强错误处理)
    if (addServiceForm) {
        addServiceForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            // 获取表单数据
            const gameType = document.getElementById('add-game-type').value;
            const serviceType = document.getElementById('add-service-type').value;
            const description = document.getElementById('add-description').value;
            const price = parseFloat(document.getElementById('add-price').value);
            const contact = document.getElementById('add-contact').value;
            const imageFiles = document.getElementById('add-images').files;
            const audioFile = document.getElementById('add-audio').files[0];

            // 验证数据
            if (!gameType || !serviceType || !description || isNaN(price) || !contact) {
                showErrorToast('请填写所有必填字段');
                return;
            }

            try {
                // 1. 获取OSS上传策略
                const policyResponse = await fetch(`${BASE_URL}/oss/policy`);
                if (!policyResponse.ok) {
                    throw new Error('获取上传凭证失败: ' + await policyResponse.text());
                }
                const policy = await policyResponse.json();
                const dir = policy.dir || 'accompany/' + Date.now() + '/';

                // 2. 上传图片
                const imageUrls = [];
                for (let i = 0; i < imageFiles.length; i++) {
                    try {
                        const file = imageFiles[i];
                        const imageUrl = await uploadFileToOss(file, policy, dir);
                        imageUrls.push(imageUrl);
                    } catch (error) {
                        console.error(`图片上传失败: ${error}`);
                        showErrorToast(`图片上传失败: ${error.message}`);
                    }
                }

                // 3. 上传音频
                let audioUrl = '';
                if (audioFile) {
                    try {
                        audioUrl = await uploadFileToOss(audioFile, policy, dir);
                    } catch (error) {
                        console.error(`音频上传失败: ${error}`);
                        showErrorToast(`音频上传失败: ${error.message}`);
                        // 即使音频失败，也继续提交表单
                    }
                }

                // 4. 创建服务数据
                const serviceData = {
                    gameType: gameType,
                    serviceType: serviceType,
                    description: description,
                    price: price,
                    contact: contact,
                    userId: userId1, // 临时用户ID
                    imageUrls: imageUrls.join(','),
                    audioUrl: audioUrl
                };

                console.log('Submitting service data:', serviceData);

                // 5. 提交服务数据
                const response = await fetch(`${BASE_URL}/accompanys`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(serviceData)
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('Service submission failed:', errorText);
                    throw new Error(`服务提交失败: ${response.status} - ${errorText}`);
                }

                const result = await response.json();

                if (result.code === 20031) { // 插入成功
                    showSuccessToast('服务添加成功！');
                    addServiceModal.style.display = 'none';
                    resetAddForm();

                    // 刷新服务列表
                    const services = await fetchAllServices();
                    renderServices(services);
                } else {
                    throw new Error(result.msg || '添加服务失败');
                }
            } catch (error) {
                console.error('添加服务失败:', error);
                showErrorToast(`添加失败: ${error.message}`);
            }
        });
    }

    // 重置添加表单
    function resetAddForm() {
        if (addServiceForm) addServiceForm.reset();
        if (imagePreview) imagePreview.innerHTML = '';
        if (audioPreview) audioPreview.innerHTML = '';
    }

    // 显示成功提示
    function showSuccessToast(message) {
        const toast = document.createElement('div');
        toast.className = 'success-toast';
        toast.innerHTML = `
            <i class="fas fa-check-circle"></i>
            <span>${message}</span>
        `;

        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }
});
